// 导入 express 等模块
const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
// 导入校验规则
const validate = require('../middleware/validatorMiddleware');
const { registerValidator, loginValidator } = require('../validators/userValidator');
const { findPasswordValidator, changePasswordValidator } = require('../validators/userValidator');
const { movieOtherValidator, sendEmailValidator } = require('../validators/userValidator')
// 导入模型
const User = require('../models/user');
const Comment = require('../models/comment');
const Movie = require('../models/movie');
const Mail = require('../models/mail');
// 导入认证中间件
const verifyToken = require('../middleware/authMiddleware');

// 注册接口
router.post('/register', registerValidator, validate, async (req, res) => {
  try {
    const { username, password, email, phone } = req.body;

    console.log("register =>", req.body);
    // 检查用户名、邮箱、手机号是否已存在
    const [existingUser, existingEmail, existingPhone] = await Promise.all([
      User.findByUsername(username),
      User.findByEmail(email),
      User.findByPhone(phone)
    ]);

    if (existingUser) {
      return res.json({
        status: 1,
        message: '用户名已被注册'
      });
    }

    if (existingEmail) {
      return res.json({
        status: 1,
        message: '邮箱已被注册'
      });
    }

    if (existingPhone) {
      return res.json({
        status: 1,
        message: '手机号已被注册'
      });
    }

    // 创建新用户
    const newUser = new User({
      username,
      password, // 密码会在保存前自动加密
      email,
      phone
    });

    await newUser.save();

    // 返回用户信息(不包含密码)
    const userResponse = {
      id: newUser._id, username, email, phone,
      createdAt: newUser.createdAt
    };

    return res.json({
      status: 0,
      message: '注册成功',
      data: userResponse
    });

  } catch (error) {
    return res.json({
      status: 1,
      message: '服务器错误，注册失败'
    });
  }
}
);

// 登录接口
router.post('/login', loginValidator, validate, async (req, res) => {
  try {
    const { username, password } = req.body;
    // 根据用户名查找用户
    const user = await User.findByUsername(username);

    if (!user) {
      return res.json({
        status: 1,
        message: '用户名或密码错误'
      });
    }
    // 验证密码是否正确
    const isValid = await user.comparePassword(password);
    if (!isValid) {
      return res.json({
        status: 1,
        message: '用户名或密码错误'
      });
    }

    // 生成token
    const token = user.generateToken();

    // 返回用户信息(不包含密码)
    const userResponse = {
      username, userId: user._id, email: user.email, phone: user.phone,
      createdAt: user.createdAt
    };
    user.isOnline = true;
    await user.save();
    return res.json({
      status: 0,
      message: '登录成功',
      isOnline: true,
      expiresTime: `${Date.now() + 7 * 24 * 60 * 60 * 1000}`,
      data: { token, user: userResponse }
    });
  } catch (error) {
    return res.json({
      status: 1,
      message: '服务器错误，登录失败'
    });
  }
});

// 用户评论接口
router.post('/postComment', verifyToken, async (req, res, next) => {
  try {
    const username = req.body.username || '匿名用户';
    const { movie_id, content } = req.body;
    let saveComment = new Comment({ username, movie_id, content });
    await saveComment.save();
    return res.json({
      status: 0,
      message: '评论成功'
    });
  } catch (error) {
    // 异常处理
    console.error('评论出错:', error);
    return res.json({
      status: 1,
      message: '服务器错误，评论失败'
    });
  }
});

// 登出接口
router.post('/logout', verifyToken, async (req, res) => {
  try {
    const user = req.user;
    user.isOnline = false;
    await user.save();
    return res.json({
      status: 0,
      message: '登出成功'
    });
  } catch (error) {
    console.error('登出出错:', error);
    return res.json({
      status: 1,
      message: '服务器错误，登出失败'
    });
  }
});

// 用户点赞
router.post('/support', movieOtherValidator, validate, verifyToken, async (req, res) => {
  try {
    const movie = await Movie.findById(req.body.movie_id);
    if (!movie) {
      return res.json({
        status: 1,
        message: '电影不存在'
      });
    }
    movie.supportCount += 1;
    await movie.save();
    return res.json({
      status: 0,
      message: '点赞成功',
      data: {
        supportCount: movie.supportCount,
        movie_id: movie._id,
        movie_name: movie.title
      }
    });
  } catch (error) {
    console.error('点赞出错:', error);
    return res.json({
      status: 1,
      message: '服务器错误，点赞失败'
    });
  }
});

// 用户找回密码
router.post('/findPassword', findPasswordValidator, validate, async (req, res) => {
  try {
    const { username, email, phone, newPassword } = req.body;
    // 根据用户名、邮箱、手机号查找用户，如果无记录，返回错误信息
    const user = await User.findByUserEmailPhone(username, email, phone);
    if (!user) {
      return res.json({
        status: 1,
        message: '邮箱、手机号与用户名三方查验失败，请检查输入是否正确'
      });
    }

    user.password = newPassword;
    await user.save();
    return res.json({
      status: 0,
      message: '密码修改成功'
    });
  } catch (error) {
    console.error('找回密码出错:', error);
    return res.json({
      status: 1,
      message: '服务器错误，找回密码失败'
    });
  }
});

// 修改密码
router.post('/changePassword', changePasswordValidator, validate, async (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const userId = decoded._id;
    const { oldPassword, newPassword } = req.body;

    // 根据用户id查找用户 
    const user = await User.findById(userId);
    if (!user) {
      return res.json({
        status: 1,
        message: '用户不存在'
      });
    }
    // 验证旧密码是否正确
    const isValid = await user.comparePassword(oldPassword);
    if (!isValid) {
      return res.json({
        status: 1,
        message: '旧密码错误'
      });
    }
    // 修改密码
    const salt = await bcrypt.genSalt(10);
    const hash = await bcrypt.hash(newPassword, salt);
    user.password = hash;
    user.isOnline = false;
    await user.save();
    return res.json({
      status: 0,
      message: '密码修改成功'
    });
  } catch (error) {
    return res.json({
      status: 1,
      message: '服务器错误，修改密码失败'
    });
  }
});

// 下载接口
router.post('/download', movieOtherValidator, validate, verifyToken, async (req, res) => {
  try {
    const movie = await Movie.findById(req.body.movie_id);
    if (!movie) {
      return res.json({
        status: 1,
        message: '电影不存在'
      });
    }
    const downloadUrl = movie.downloadUrl;
    movie.downloadCount += 1;
    await movie.save();
    return res.json({
      status: 0,
      message: '下载成功',
      data: {
        downloadUrl, title: movie.title, downloadCount: movie.downloadCount
      }
    });
  } catch (error) {
    return res.json({
      status: 1,
      message: '服务器错误，下载失败'
    });
  }
});


// 用户发送站内信
router.post('/sendEmail', sendEmailValidator, validate, verifyToken, async (req, res) => {
  // 获取当前的用户状态
  const user = req.user;
  const sender = user.email;
  const { receiver, subject, content } = req.body;
  try {
    // 检查接收方是否存在
    const receiverUser = await User.findByEmail(receiver);
    if (!receiverUser) {
      return res.json({ status: 1, message: '接收方不存在' });
    }
    // 发送邮件
    const mail = new Mail({ sender, receiver, subject, content });
    await mail.save();
    return res.json({ status: 0, message: '邮件发送成功' });
  } catch (error) {
    console.error('发送邮件出错:', error);
    return res.json({ status: 1, message: '服务器错误，邮件发送失败' });
  }
});

// 显示站内信 isReceive=0时显示发送内容 =1时显示收到的内容
router.post('/showEmail', verifyToken, async (req, res, next) => {
  // 处理用户状态
  const user = req.user;
  const isReceive = req.body['isReceive'] || 0;
  const email = user.email;
  try {
    if (isReceive == 0) {
      const sendEmails = await Mail.findBySender(email);
      return res.json({
        status: 0,
        message: '获取邮件成功',
        data: sendEmails
      });
    } else if (isReceive == 1) {
      const receiveEmails = await Mail.findByReceiver(email);
      return res.json({
        status: 0,
        message: '获取邮件成功',
        data: receiveEmails
      });
    } else {
      return res.json({
        status: 1,
        message: '参数错误'
      });
    }
  } catch (error) {
    console.error('获取邮件出错:', error);
    return res.json({ status: 1, message: '服务器错误，获取邮件失败' });
  }
});

// 显示用户主页信息
router.post('/showUserInfo', verifyToken, async (req, res) => {
  const user = req.user;
  return res.json({
    status: 0,
    message: '获取用户信息成功',
    data: { ...user._doc, password: '***********' }
  });
});

// 获取MD5值
function getMD5Password(id) {
  var md5 = crypto.createHash('md5');
  md5.update(id + init_token);
  return md5.digest('hex');
};


module.exports = router;
